package com.gcpproxy.auth;

import com.gcpproxy.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * Bearer Token认证提供者
 */
@Component
public class BearerTokenAuthenticationProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(BearerTokenAuthenticationProvider.class);

    @Autowired
    private AppConfig appConfig;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!appConfig.getAuth().isEnabled()) {
            logger.debug("认证已禁用，跳过token验证");
            return new BearerTokenAuthentication(authentication.getCredentials().toString(), Collections.emptyList());
        }

        String token = authentication.getCredentials().toString();
        
        if (verifyToken(token)) {
            logger.debug("Token验证成功");
            return new BearerTokenAuthentication(token, Collections.emptyList());
        } else {
            logger.warn("Token验证失败: {}", token.substring(0, Math.min(10, token.length())) + "...");
            throw new BadCredentialsException("无效的Token");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return BearerTokenAuthentication.class.isAssignableFrom(authentication);
    }

    /**
     * 验证token
     * 使用配置文件中的token列表进行验证
     */
    private boolean verifyToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            logger.debug("Token为空或null");
            return false;
        }
        
        // 使用配置文件中的token验证方法
        boolean isValid = appConfig.getAuth().isValidToken(token);
        
        if (isValid) {
            logger.debug("Token验证通过: {}...", token.substring(0, Math.min(8, token.length())));
        } else {
            logger.debug("Token验证失败: {}...", token.substring(0, Math.min(8, token.length())));
        }
        
        return isValid;
    }
}